#!/bin/bash
# SchedulerAI Docker Image Build Script

set -e

# Configuration
IMAGE_NAME="scheduler-ai"
IMAGE_TAG="${1:-latest}"
BUILD_CONTEXT="../"
DOCKERFILE="Dockerfile"

echo "Building SchedulerAI Docker Image"
echo "=================================="
echo "Image: $IMAGE_NAME:$IMAGE_TAG"
echo "Context: $BUILD_CONTEXT"
echo "Dockerfile: $DOCKERFILE"
echo ""

# Change to project root directory
cd "$(dirname "$0")/.."

# Build the Docker image
echo "Starting Docker build..."
docker build \
    -t "$IMAGE_NAME:$IMAGE_TAG" \
    -f "$DOCKERFILE" \
    --build-arg BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
    --build-arg VCS_REF="$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" \
    --build-arg VERSION="$IMAGE_TAG" \
    .

echo ""
echo "Build completed successfully!"
echo "Image: $IMAGE_NAME:$IMAGE_TAG"

# Display image information
echo ""
echo "Image Information:"
echo "=================="
docker images "$IMAGE_NAME:$IMAGE_TAG" --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"

# Optional: Run basic validation
if [ "$2" = "--validate" ]; then
    echo ""
    echo "Running validation tests..."
    echo "=========================="
    
    # Test image can start
    echo "Testing image startup..."
    CONTAINER_ID=$(docker run -d --rm -p 8001:8000 "$IMAGE_NAME:$IMAGE_TAG")
    
    # Wait for startup
    sleep 10
    
    # Test health endpoint
    echo "Testing health endpoint..."
    if curl -f http://localhost:8001/health >/dev/null 2>&1; then
        echo "Health check passed"
    else
        echo "Health check failed"
    fi
    
    # Cleanup
    docker stop "$CONTAINER_ID" >/dev/null
    echo "Validation completed"
fi

echo ""
echo "To run the container:"
echo "docker run -p 8000:8000 $IMAGE_NAME:$IMAGE_TAG"
echo ""
echo "To run with docker-compose:"
echo "docker-compose up -d"